package JUC.printWhen5;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * @className: SemaphoreList
 * @Description:
 * @Author: wangyifei
 * @Date: 2022/9/5 16:43
 */
public class SemaphoreList {
    private List<Integer> list = new ArrayList<>();
    public void add(Integer i){
       list.add(i) ;
    }
    public int size(){
        return list.size();
    }
    public static void main(String[] args) {
        Semaphore lock = new Semaphore(0);
        Semaphore lock2 = new Semaphore(0);
        SemaphoreList list = new SemaphoreList();
        Thread t1 = new Thread(() -> {
            try {
                lock.acquire();
                System.out.println("list size is " + list.size());
                lock2.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread t2 = new Thread(() -> {
            try {
                for(int i = 0 ; i < 10 ; i++){
                    list.add(i);
                    System.out.println("add " + i);
                    if(list.size() == 4){
                        lock.release();
                        lock2.acquire();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
